#include <gui/gamewidget.h>

#include <game/gameserver.h>
#include <game/gameclient.h>
#include <game/game.h>
#include <game/keymanager.h>
#include <gui/paintmanager.h>
#include <gui/statemanager.h>
#include <gui/gamescene.h>
#include <gui/mainmenustate.h>

#include <QtOpenGL/qgl.h>

#include <QPainter>
#include <QKeyEvent>
#include <QBrush>
#include <QPen>
#include <QApplication>
#include <QDomDocument>
#include <QFile>

#include <cmath>

//#include <QElapsedTimer>

GameWidget::GameWidget(bool /*isServer*/, QString /*addr*/, quint16 /*port*/,  QWidget *parent) :
    QGLWidget(parent)
{
    zoomFactor = 1;
    myKeyManager = new KeyManager(this);
    myStateManager = new StateManager(this);

    MainMenuState *menuState = new MainMenuState(myStateManager, myKeyManager, this);

    //myPaintManager = new PaintManager(state->getScene(), this);
    //connect(myPaintManager, SIGNAL(updated()), this, SLOT(updateGL()));

    myStateManager->pushState(menuState);

    //myPaintManager->setScene(menuState->getScene());
    //myGame = state->getGame();

    //if (isServer) {
    //    myGame = new GameServer(myKeyManager, this);
        //myGame = new Game(myKeyManager, this);
    //} else {
    //    myGame = new GameClient(myKeyManager, addr, port, this);
    //}
    //myGame = new Game(myKeyManager, this);
    connect(myStateManager, SIGNAL(updated()), this, SLOT(update()));
}

GameWidget::~GameWidget() {
}

void GameWidget::initializeGL() {
    qglClearColor(QColor("black"));
    glClearDepth(1.0);				// Enables Clearing Of The Depth Buffer
    glEnable(GL_TEXTURE_2D);

    glEnable(GL_TEXTURE_3D);

    glFrontFace(GL_CCW);	 // Counter clock-wise polygons face out

    //glEnable(GL_DEPTH_TEST);	// Hidden surface removal
    //glEnable(GL_ALPHA_TEST);
    //glAlphaFunc(GL_GREATER,0.1);

    glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);					// Enable Blending
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    //gluPerspective(45, 1, 0.1, 100);
    glOrtho(0.0f, 1280, 800, 0.0f, -1.0f, 1.0f);
    glMatrixMode(GL_MODELVIEW);
}

void GameWidget::paintGL() {
    myStateManager->getPaintManager()->paintScene(width(), height(), this);
}

void GameWidget::resizeGL(int width, int height) {
    glViewport(-width, -height, width * 2, height * 2);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    //gluPerspective(45, width / (double)height, 0.1, 10000);
    glOrtho(-width, width, -height, height, -10.0f, 10.0f);

    glMatrixMode(GL_MODELVIEW);
}


void GameWidget::keyPressEvent(QKeyEvent *e) {
    myKeyManager->keyPressed((Qt::Key)e->key());
}

void GameWidget::keyReleaseEvent(QKeyEvent *e) {
    myKeyManager->keyReleased((Qt::Key)e->key());
}
